<template>
  <view class="update-app-area" v-if="update">
    <view class="update-app-main" v-bind:style="'top:'+layer_top+'px;opacity:'+layer_opacity+';'">
      <image src="http://zhsh-package.oss-cn-hangzhou.aliyuncs.com/images/net.zhsh.waimai/update_bg_top.png"
        v-bind:style="'height:'+bg_top_height+'px;'" @load="imageLoad" mode="aspectFit" class="update-app-bg" />
      <view class="update-app-close" @tap="updateAppClose"></view>
      <view class="update-app-h1">发现新版本</view>
      <view class="update-app-version-code">
        <view class="update-app-version-code-bg"></view>
        <view class="update-app-version-code-main">{{new_version.version_name}}</view>
      </view>
      <view class="update-app-version-msg">
        <text>{{new_version.version_update_msg||"优化一些用户体验"}}</text>
      </view>
      <view class="update-app-bottom">
        <view class="update-app-button-area" v-bind:style="'background-color:'+button_area_bg_color+';'">
          <view class="update-app-button-speed" :style="'width:'+speed+'%;'"></view>
          <view class="update-app-button-text" @tap="android_update">
            {{button_text}}
            {{status=='down'?'('+speed+' %)':''}}
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: "GgUpdateApp",
  props: {
    check: {
      type: Boolean,
      default: false
    },
    flagGet: {
      typ: String,
      default: ''
    },
    flagGetParam: {
      typ: Object,
      default: {}
    },
    maskTop: {
      type: Boolean,
      default: true
    },
    maskBottom: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    check() {
      if (this.check) {

        // #ifdef APP-PLUS
        // 检测升级
        this.app_update();
        // #endif
      }
    },
    status() {
      switch (this.status) {
        case 'wait':

          break;
        case 'down':
          this.button_text = '正在下载'
          this.button_area_bg_color = 'rgba(47,146,215,0.3)'
          break;
        case 'over':
          this.button_text = '立即安装'
          break;
      }
    },
    button_text() {
    },
    update() {
      if (this.update) {
        this.openPlusMask()
      } else {
        this.closePlusMask()
      }
    }
  },
  data() {
    return {
      update: false,
      layer_opacity: 0,
      bg_top_img: 'http://zhsh-package.oss-cn-hangzhou.aliyuncs.com/images/net.zhsh.waimai/update_bg_top.png',
      new_version: {},
      bg_top_height: 0,
      window_width: 0,
      speed: 0,//app下载进度
      progress: 0,//实际下载进度
      speedTimer: 0,
      status: 'wait',//wait:待更新，down:正在下载，over:下载完成
      button_text: '立即更新',
      layer_top: 100,
      button_area_bg_color: 'rgba(47,146,215,1)',//按钮区背景
      package_temp_path: '',//安装包缓存地址
      net_work_type: '',
      net_work_wifi: true,
      plus_mask: {
        top: '',
        bottom: '',
      }
    };
  },
  created() {
    if (this.update) {
      this.openPlusMask();
    }

    if (this.check) {

      // #ifdef APP-PLUS
      // 检测升级
      this.app_update();
      // #endif
    }
  },
  methods: {
    /* 监听图片是否完成加载 */
    imageLoad() {
      this.initBgTopWidth();
    },
    /* 计算顶部背景图高度 */
    initBgTopWidth() {
      const res = uni.getSystemInfoSync();
      this.window_width = res.windowWidth
      uni.getImageInfo({
        src: this.bg_top_img,
        success: (image) => {
          this.bg_top_height = (this.window_width * 0.8) / image.width * image.height
          setTimeout(() => {
            this.layer_opacity = 1;
            this.initLayer();
          }, 500)
        }
      });
    },
    /* 计算弹窗整体高度 、 matop*/
    initLayer() {
      const res = uni.getSystemInfoSync();
      let window_height = res.windowHeight;
      uni.createSelectorQuery().in(this).select('.update-app-main').boundingClientRect((data) => {
        this.layer_top = (window_height - data.height) / 2;

      }).exec();
    },
    app_update() {
      switch (uni.getSystemInfoSync().platform) {
        case 'ios':
          break;
        case 'android':
          this.check_android_version();
          break
      }
    },
    /* 检测android版本 */
    check_android_version() {
      if (!this.flagGet) {
        plus.nativeUI.toast("请设置flagGet属性");
        return;
      }
      const version_code = plus.runtime.versionCode
      let flagGetParam = { ...this.flagGetParam }
      flagGetParam.current_version_code = version_code
      flagGetParam.version_os = 'android'
      this.$request.flagGet(this.flagGet, flagGetParam).then((result) => {
        let new_version = {};
        if (result.data) {
          new_version = result.data[0];
          this.new_version = new_version;
          if (new_version.version_code > version_code && new_version.version_download_url) {
            this.update = true;
          }
          this.$emit('version', new_version)
        } else {
          this.$emit('version', '')
        }
      });
    },
    android_update() {
      switch (this.status) {
        case 'wait'://'立即更新' ,点击即下载
          this.checkNetWork();
          break;
        case 'not_wifi'://'立即更新' ,点击即下载
          this.android_apk_down();
          break;
        case 'down':
          plus.nativeUI.toast("下载中，请耐心等待...");
          break;
        case 'over':
          this.install_apk();
          break;
      }
    },
    checkNetWork() {
      console.log('checkNetWork')
      uni.getNetworkType({
        success: (res) => {
          if (res.networkType == 'wifi') {
            this.android_apk_down();
            return;
          }
          plus.nativeUI.toast("当前网络环境是" + res.networkType + '，下载流量费用由运营商收取');
          this.status = 'not_wifi';
          this.button_text = '使用数据流量下载';
        }
      })
    },
    android_apk_down() {
      this.status = 'down';
      const downloadTask = uni.downloadFile({
        url: this.new_version.version_download_url, //仅为示例，并非真实的资源
        success: (res) => {
          if (res.statusCode === 200) {
            this.package_temp_path = res.tempFilePath;
            this.status = 'over';
          } else {
            this.android_apk_down_fail();
          }
        },
        fail: () => {
          this.android_apk_down_fail();
        }
      });
      downloadTask.onProgressUpdate((res) => {
        if (res.progress != this.speed) {
          this.speed = res.progress;
        }
      });
    },
    //下载失败
    android_apk_down_fail() {
      this.status = 'wait';
      this.button_text = '下载失败，请重试...';
      this.button_area_bg_color = 'rgba(255,0,0,1)';//按钮区背景
      this.speed = 0;
    },
    install_apk() {
      plus.runtime.openFile(this.package_temp_path);
    },
    /* 关闭更新弹窗 */
    updateAppClose() {
      if (this.new_version.version_must == 'on' || this.new_version.version_force == 'on') {
        /* 必须更新版本，或强制更新版本 关闭即推出 */
        plus.runtime.quit();
        return;
      }
      this.update = false;
    },
    openPlusMask() {

      const system_info = this.system_info || uni.getSystemInfoSync();
      console.log(system_info);
      let plus_mask = this.plus_mask || {};

      if (this.maskTop == true) {
        plus_mask.top = new plus.nativeObj.View('top', { top: '0px', left: '0px', height: (system_info.statusBarHeight + 45) + 'px', width: '100%', backgroundColor: 'rgba(0, 0, 0, 0.2)' });
        plus_mask.top.show();
      }
      if (this.maskBottom == true) {
        plus_mask.bottom = new plus.nativeObj.View('bottom', { bottom: '0px', left: '0px', height: '50px', width: '100%', backgroundColor: 'rgba(0, 0, 0, 0.2)' });
        plus_mask.bottom.show();
      }
    }
    ,
    closePlusMask() {
      if (this.maskTop == true) {
        this.plus_mask.top.close();
      }
      if (this.maskBottom == true) {
        this.plus_mask.bottom.close();
      }
    }
  }
};
</script>

<style>
.update-app-area {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.2);
  z-index: 9999999999999999;
  padding-bottom: 10%;
}
.update-app-close {
  position: absolute;
  right: 10px;
  top: 54px;
  width: 30px;
  height: 30px;
}
.update-app-main {
  width: 80%;
  position: absolute;
  top: 100px;
  left: 10%;
  transition: all 0.3s;
}
.update-app-bg {
  width: 100%;
}
.update-app-h1 {
  background: #ffffff;
  font-size: 16px;
  text-align: center;
  width: 100%;
  margin-top: -10px;
  padding: 10px 0 10px;
}
.update-app-version-code {
  background: #ffffff;
  height: 30px;
  position: relative;
  text-align: center;
}
.update-app-version-code-bg {
  height: 1px;
  background: rgba(0, 0, 0, 0.1);
  width: 90%;
  position: absolute;
  left: 5%;
  top: 15px;
}
.update-app-version-code-main {
  display: inline;
  background: #ffffff;
  position: relative;
  line-height: 30px;
  padding: 0 5px;
  font-size: 14px;
}
.update-app-version-msg {
  font-size: 14px;
  color: #666666;
  padding: 10px 10%;
  background: #ffffff;
}
.update-app-bottom {
  background: #ffffff;
  border-bottom-left-radius: 10px;
  border-bottom-right-radius: 10px;
  padding: 10px 10% 20px;
}
.update-app-button-area {
  width: 100%;
  height: 35px;
  border-radius: 20px;
  overflow: hidden;
  position: relative;
}
.update-app-button-text {
  position: absolute;
  color: #ffffff;
  font-size: 14px;
  text-align: center;
  line-height: 35px;
  top: 0;
  left: 0;
  width: 100%;
  height: 35px;
}
.update-app-button-speed {
  position: absolute;
  left: 0;
  top: 0;
  height: 35px;
  transition: width 0.3s;
  background: #2f92d7;
}
</style>
